import { Fragment, useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import { getBlogs } from "../../api/blogApi";
import { Blog, BlogStatus } from "../../api/types";
import { primaryColor } from "../../context/ThemeProvide";
import Link from "next/link";
import BlogCard from "./BlogCard";
import { ContentWidth, fadeIn } from "../commentStyled";
import "../../constant/VanillaTilt";

const BlogList = () => {
  const [blogList, setBlogList] = useState<Blog[] | []>([]);

  const getBlogList = useCallback(async () => {
    const { data } = await getBlogs({
      find: { status: BlogStatus["PUBLIC"] },
      sort: { createAt: -1 },
      verify: false,
      limit: 5,
    });
    if (!data) return;
    const { counts, blogs } = data;
    blogs && setBlogList(blogs);
    VanillaTilt.init(document.querySelectorAll(".blogCard"));
  }, []);

  useEffect(() => {
    getBlogList();
  }, [getBlogList]);

  return (
    <Fragment>
      {blogList.length ? (
        <Container>
          {blogList.map((blog: Blog) => (
            <BlogCard blog={blog} key={blog._id} />
          ))}
          <Link href="/blogList" passHref>
            <MoreBlog>更多 前往 博文列表</MoreBlog>
          </Link>
        </Container>
      ) : null}
    </Fragment>
  );
};

export default BlogList;

const MoreBlog = styled.span`
  text-align: center;
  font-size: 1.2rem;
  color: #fff;
  margin: 0 auto;
  transition: all 0.3s linear;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    color: ${primaryColor};
    transform: translateY(-1px);
    letter-spacing: 1px;
    text-shadow: 0 0 20px ${props => props.theme.shadow};

    &::after {
      left: 0;
    }
  }

  &::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px;
    background: linear-gradient(60deg, #51f, #fff, #3700ff);
    bottom: 0;
    left: -100%;
    transition: left 0.3s linear;
  }
`;

const Container = styled.div`
  ${ContentWidth};
  padding: 1rem;
  min-height: 10rem;
  /* border: 1px dashed #ddd; */
  margin-bottom: 5rem;
  display: flex;
  flex-direction: column;
  animation: ${fadeIn} 0.3s linear;
`;
